/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MODEL.CONTROLLER;

import MODEL.DAO.*;
import MODEL.POJO.*;
import java.awt.Desktop.Action;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 *
 * @author kijoo
 */
@WebServlet(name = "CartAppleController", urlPatterns = {"/CartAppleController"})
public class CartAppleController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("Action");
        if (action != null) {
            String idloaisanpham = "";
            idloaisanpham = request.getParameter("idloaisanpham");
            request.setAttribute("LoaiSanPhams", idloaisanpham);
            ArrayList<LoaiDanhMucPOJO> loaidanhmuc = LoaiDanhMucDAO.LayDanhSachLoaiDanhMuc(idloaisanpham);
            request.setAttribute("LoaiDanhMucs", loaidanhmuc);
            ArrayList<ChiTietHoaDonPOJO> giohang = null;
            request.setAttribute("Error", null);
            HttpSession session = request.getSession();
            int idchitietsanpham = 0;
            if (request.getParameter("idchitietsanpham") != null) {
                idchitietsanpham = Integer.parseInt(request.getParameter("idchitietsanpham"));
            }
            if (action.equals("ChoVaoGioHang")) {
                if (idloaisanpham != "" || idchitietsanpham != 0) {
                    if (session.getAttribute("GioHang") == null) {
                        giohang = new ArrayList<ChiTietHoaDonPOJO>();
                        session.setAttribute("GioHang", giohang);
                    } else {
                        giohang = (ArrayList<ChiTietHoaDonPOJO>) session.getAttribute("GioHang");
                    }
                    boolean kq = false;
                    for (int i = 0; i < giohang.size(); i++) {
                        ChiTietHoaDonPOJO cthd = giohang.get(i);
                        if (cthd.getIdchitietsanpham() == idchitietsanpham) {
                            cthd.setSoluongban(cthd.getSoluongban() + 1);
                            kq = true;
                            break;
                        }
                    }
                    if (kq == false) {
                        ChiTietHoaDonPOJO cthd = new ChiTietHoaDonPOJO();
                        cthd.setIdchitietsanpham(idchitietsanpham);
                        cthd.setSoluongban(1);
                        giohang.add(cthd);
                        session.setAttribute("GioHang", giohang);
                    }
                } else {
                    request.setAttribute("Error", "co loi xay ra !!!");

                }
                ArrayList<TinTucPOJO> dstt = TinTucDAO.LayTinMoiXuatHien();
                    request.setAttribute("DanhSachTinTuc", dstt);
                request.getRequestDispatcher("/CartApple.jsp").forward(request, response);
            } else if (action.equals("Xoa")) {
                if (session.getAttribute("GioHang") != null) {
                    giohang = (ArrayList<ChiTietHoaDonPOJO>) session.getAttribute("GioHang");
                    for (int j = 0; j < giohang.size(); j++) {
                        ChiTietHoaDonPOJO cthd = giohang.get(j);
                        int test = cthd.getIdchitietsanpham();
                        if (idchitietsanpham == test) {
                            giohang.remove(j);
                            break;
                        }
                    }
                }
                session.setAttribute("GioHang", giohang);
                request.getRequestDispatcher("/CartApple.jsp").forward(request, response);
            } else if (action.equals("CapNhatGioHang")) {
                request.getRequestDispatcher("/CartApple.jsp").forward(request, response);
            } else if (action.equals("NhapThongTin")) {
                giohang = (ArrayList<ChiTietHoaDonPOJO>) session.getAttribute("GioHang");
                if (giohang.size() == 0) {
                    request.setAttribute("Error", "Ban chua co mon hang nao trong gio !!!");
                }
                request.setAttribute("GiaTriNhapThongTin", "1");
                ArrayList<TinTucPOJO> dstt = TinTucDAO.LayTinMoiXuatHien();
                    request.setAttribute("DanhSachTinTuc", dstt);
                request.getRequestDispatcher("/CartApple.jsp").forward(request, response);
            } else if (action.equals("DatHang")) {
                request.setAttribute("ThanhCong", null);
                String hoten = request.getParameter("hoten");
                String diachi = request.getParameter("diachi");
                String dienthoai = request.getParameter("dienthoai");
                String email = request.getParameter("email");
                String hotennguoinhan = request.getParameter("hotennguoinhan");
                String diachinguoinhan = request.getParameter("diachinguoinhan");
                String dienthoainguoinhan = request.getParameter("dienthoainguoinhan");
                String emailnguoinhan = request.getParameter("emailnguoinhan");
                giohang = (ArrayList<ChiTietHoaDonPOJO>) session.getAttribute("GioHang");
                BigDecimal tongtien = null;
                for (int i = 0; i < giohang.size(); i++) {
                    ChiTietHoaDonPOJO cthd = giohang.get(i);
                    ChiTietSanPhamPOJO ctsp = ChiTietSanPhamDAO.LayChiTietSanPham(cthd.getIdchitietsanpham());
                    BigDecimal thanhtien;
                    thanhtien = (new BigDecimal(cthd.getSoluongban())).multiply(ctsp.getGiaban());
                    tongtien = thanhtien;
                }
                HoaDonPOJO hd = new HoaDonPOJO();
                hd.setThanhtien(tongtien);
                hd.setHotennguoimua(hoten);
                hd.setDiachi(diachi);
                hd.setEmail(email);
                hd.setSodienthoai(dienthoai);
                hd.setHotennguoinhan(hotennguoinhan);
                hd.setDiachinguoinhan(diachinguoinhan);
                hd.setEmailnguoinhan(emailnguoinhan);
                hd.setSodienthoainguoinhan(dienthoainguoinhan);
                Boolean kq = HoaDonDAO.ThemHoaDon(hd);
                int flag = 1;
                if (kq == true) {
                    int mhd = HoaDonDAO.LayMaHoaDonMoiNhat();
                    ChiTietHoaDonPOJO cthd1 = new ChiTietHoaDonPOJO();
                    for (int i = 0; i < giohang.size(); i++) {
                        cthd1 = giohang.get(i);
                        cthd1.setIdhoadon(mhd);
                        boolean kq1 = ChiTietHoaDonDAO.ThemChiTietHoaDon(cthd1);
                        if (kq1 == false) {
                            flag = 0;
                        }
                    }
                    if (flag == 0) {
                        Boolean kq1 = ChiTietHoaDonDAO.XoaChiTietHoaDon(mhd);
                        if (kq1 == true) {
                            Boolean kq2 = HoaDonDAO.XoaHoaDon(mhd);
                            if (kq2 == false) {
                                request.setAttribute("Error", " Loi khi xoa hoa don");
                            }
                        } else {
                            request.setAttribute("Error", " lỗi trong khi xoa chi tiet hoa don");
                        }
                        request.setAttribute("Error", "Có lỗi trong quá trình đặt hàng 1");
                    } else {
                        int solanmua=0;
                        ChiTietHoaDonPOJO cthd2 = new ChiTietHoaDonPOJO();
                        for (int i = 0; i < giohang.size(); i++) {
                            cthd2 = giohang.get(i);
                            ChiTietSanPhamPOJO ctsp1 = ChiTietSanPhamDAO.LayChiTietSanPham(cthd2.getIdchitietsanpham());
                            solanmua=ctsp1.getSolanmua()+cthd2.getSoluongban();
                            boolean kq3 = ChiTietSanPhamDAO.ThemSoLanMua(ctsp1.getIdchitietsanpham(), solanmua);                           
                        }
                        request.setAttribute("ThanhCong", "Đặt mua hàng thành công");
                        session.invalidate();
                    }
                } else {
                    request.setAttribute("Error", "Có lỗi trong quá trình đặt hàng");
                }
                ArrayList<TinTucPOJO> dstt = TinTucDAO.LayTinMoiXuatHien();
                    request.setAttribute("DanhSachTinTuc", dstt);
                request.getRequestDispatcher("/ThongBaoDatHangApple.jsp").forward(request, response);
            }

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
